package com.mocha.auth.service;

import com.coffee.security.CoffeeAuthUser;
import com.coffee.security.CoffeeUser;
import com.coffee.security.CoffeeUserBO;
import com.coffee.security.SecurityConstants;
import com.mocha.auth.handler.CoffeeUserDetailsLoadHandler;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户详细信息
 *
 * @author songkui
 * @since 2025-4-17
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class CoffeeUserDetailsMobileServiceImpl implements CoffeeUserDetailsService {

	private final CoffeeUserDetailsLoadHandler coffeeUserDetailsLoadHandler;

//	private final CacheManager cacheManager;

	/** clientId:mobile */
//	@Override
//	@SneakyThrows
//	public UserDetails loadUserByUsername(String mobile) {
//		Cache cache = cacheManager.getCache(SecurityConstants.USER_DETAILS);
//		if (cache != null && cache.get(mobile) != null) {
//			return (CoffeeAuthUser) Objects.requireNonNull(cache.get(mobile)).get();
//		}
//
//		CoffeeUser coffeeUser = coffeeUserDetailsLoadHandler.handle(CoffeeUserBO.builder().mobile(mobile).build());
//		UserDetails userDetails = getUserDetails(coffeeUser);
//		if (cache != null) {
//			cache.put(mobile, userDetails);
//		}
//		return userDetails;
//	}

	/** clientId:mobile */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String mobile) {
		CoffeeUserBO coffeeUserBO;
		if (mobile.contains(":")){
			String [] split = mobile.split(":");
			coffeeUserBO = CoffeeUserBO.builder().mobile(split[1]).clientId(split[0]).build();
		}else {
			coffeeUserBO = CoffeeUserBO.builder().mobile(mobile).build();
		}

		CoffeeUser coffeeUser = coffeeUserDetailsLoadHandler.handle(coffeeUserBO);
		return getUserDetails(coffeeUser);
	}


	/**
	 * 是否支持此客户端校验
	 */
	@Override
	public boolean support(String clientId, String grantType) {
		return SecurityConstants.MOBILE.equals(grantType);
	}

}
